<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use EasyWeChat\Factory;
use app\common\controller\Api;
use think\Session;
use app\admin\model\weixin\WeixinUser;
use think\Cookie;
class Special extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
   /**
     * 公共
     * @author gzy
     * @date   2018年8月12日 09:15:00
     */
    public function _initialize(){
        parent::_initialize();
       //Session::set('wechat_openid','oQUyLs1BzzHCfkY7W8SUuWucxtbo');
        if((!Session::get('wechat_openid') && !in_array($this->request->action(),array("login","oauth","index")))){
            header("Location:".$this->request->domain().'/index/special/oauth');
        }
        $this->WeixinModel = new WeixinUser();
        $this->modelspe = new \app\admin\model\serial\Special;
        $this->modelLog = new \app\admin\model\serial\SpecialLog;
        $this->modelman = new \app\admin\model\Management;
        $this->app = Factory::officialAccount(config('wechat'));
        $this->pdfurlarr = $this->modelspe->getPdfUrlList();
    }

   
    public function index(){
       Cookie::delete("wechat_type");
       Cookie::set('wechat_type', $this->request->get('type', "lists"));
       if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') == false || !Session::get('wechat_openid')) {
          return redirect($this->request->domain().'/index/special/oauth');
       }
       return redirect($this->request->domain().'/index/special/'.Cookie::get('wechat_type'));
       // 检测是否需要验证登录
        
    } 
    public function lists(){
      $userid = TableField('WeixinUser','userid',Session::get('wechat_openid'),'openid');
      $spinfo = $this->modelspe->where(array('userid'=>$userid))->find();
      if($spinfo)  header("Location:".$spinfo['pdf_url_text']);
      if ($this->request->isPost()) {
             $params = $this->request->post();
             $speinfo = $this->modelspe->where(array('code'=>$params['code'],'is_use'=>1,'is_cancel'=>1))->find();
             if(!$speinfo) $this->error('此账号为个人专属账号，请使用首次提交时的微信领取');
            if ($params) {
               $params['usetime'] = time();
               $params['is_use'] = 2;
               $params['is_send'] = 2;
               $params['userid'] = $userid;
               $data = [
                  'text' => $params['userid'].'输入账号'.$params['code'],
                  'type' => 2,
                  'relation_id' => $speinfo['id'],
               ];
              // print_r($this->Booksmodel->getLastSql());die;
                try {
                    $result = $this->modelspe->save($params,['id'=>$speinfo['id']]);
                    if ($result !== false) {
                        $log = $this->modelLog->create($data);
                       $this->success('','',$this->pdfurlarr[$params['type_pdf']]);
                    } else {
                        $this->error($this->Booksmodel->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
      return $this->view->fetch();
    }
    public function add(){
      $userid = TableField('WeixinUser','userid',Session::get('wechat_openid'),'openid');
      if ($this->request->isPost()) {
             $params = $this->request->post();
             $where = " consigneePhone = '".$params['tel']."'";
             $speinfo = TableListSqlQuery('Management',$where,'id');
            if(!$speinfo) $this->error('','',2);
            if ($params) {
         
               $userinfo['name'] = $params['name'] = $params['username'];
               $userinfo['phone'] = $params['tel'];
               $params['userid'] = $userid;
               $params['gift'] = 2;
               unset($params['tel'],$params['username']);
               $data = [
                  'text' => $userid.'申领订单id：'.$speinfo[0]['id'].'手机号：'.$userinfo['phone'],
                  'type' => 3,
                  'relation_id' => $speinfo[0]['id'],
               ];
              // print_r($this->Booksmodel->getLastSql());die;
                try {
                    $result = $this->modelman->save($params,['id'=>$speinfo[0]['id']]);
                    if ($result !== false) {
                       $log = $this->modelLog->create($data);
                       $result = $this->WeixinModel->save($userinfo,['userid'=>$userid]);
                       $this->success('','',1);
                    } else {
                        $this->error($this->Booksmodel->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
      return $this->view->fetch();
    }
    public function login(){
        $user = $this->app->oauth->user();
        $userinfo = $user->toArray();
        if($userinfo){
          if(!TableField('WeixinUser','userid',$userinfo['id'],'openid')){
              $params = $userinfo['original'];
              unset($params['privilege'],$params['language']);
              $accessToken = $this->app->access_token;
              $access_token = $accessToken->getToken(true);
              $params['access_token'] = $access_token['access_token']??'';
              $params['expires_in'] = $access_token['expires_in']??7200;
              $result = $this->WeixinModel->save($params);
              if(!$result){
                  $this->error(__('请重新登录'));
              }
          }
          Session::set('wechat_openid',$user->getId());
          return redirect($this->request->domain().'/index/special/'.Cookie::get('wechat_type'));
        }else{
          $this->error(__('请联系客服'));
        }
    }
   public function oauth(){
       $response = $this->app->oauth->scopes(['snsapi_userinfo'])->redirect();
        $response->send();exit;
    }

  

}
